package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("region")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        return "region/list";
    }

    @RequestMapping("getParentId")
    @ResponseBody
    public List<Map> getParentId(Long id) {
        List<Region> list = regionService.getParentId(id);
        //返回treeview指定的格式
        List<Map> treeList = new ArrayList<>();
        for (Region region : list) {
            treeList.add(region.toTreeViewMap());
        }
        return treeList;
    }

    //查询所有子节点数据集合
    @RequestMapping("listChildRegion")
    @ResponseBody
    public List<Region> listChildRegion(Long id) {
        return regionService.getParentId(id);
    }

    //更新地区信息
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region region) {
        JSONResult result = new JSONResult();
        try {
            if (region.getId() != null) {
                regionService.update(region);
            } else {
                regionService.save(region);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    //更新推荐状态
    @RequestMapping("updateState")
    @ResponseBody
    public JSONResult updateState(Integer state, Long id) {
        JSONResult result = new JSONResult();
        try {
            if (id != null) {
                regionService.updateSate(state, id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @RequestMapping("listAll")
    @ResponseBody
    public List<Region> listAll() {
        return regionService.listAll(null);
    }
}
